#include <MoveComponent.h>
#include <TransformComponent.h>
#include <EventManager.h>
#include <CoreEvents.h>
#include <Actor.h>
#include <ALEstd.h>

const char* MoveComponent2D::g_name = "MoveComponent2D";
const ComponentId& MoveComponent2D::g_ID = ActorComponent::GetIdFromName(MoveComponent2D::g_name);

#pragma warning( disable : 4244)

bool MoveComponent2D::VInit(tinyxml2::XMLElement* pData)
{
	tinyxml2::XMLElement* pVelocityElement = pData->FirstChildElement("Velocity");
	if (pVelocityElement)
	{
		double x = 0;
		double y = 0;
		pVelocityElement->QueryDoubleAttribute("x", &x);
		pVelocityElement->QueryDoubleAttribute("y", &y);

		m_velocity = Vec2(x, y);
	}
	tinyxml2::XMLElement* pAngularElement = pData->FirstChildElement("AngularVelocity");
	if (pAngularElement)
	{
		pAngularElement->QueryDoubleAttribute("angle", &m_angularVelocity);
	}

	return true;
}

void MoveComponent2D::VUpdate(double deltaSecs)
{
	std::weak_ptr<TransformComponent2D> pWeakTrans = m_pOwner->GetComponent<TransformComponent2D>(TransformComponent2D::g_ID);

	if (std::shared_ptr<TransformComponent2D> pTrans = pWeakTrans.lock())
	{
		Vec2 position = pTrans->GetPosition();
		position += m_velocity *deltaSecs;

		double angle = pTrans->GetOrientation();
		Vec2 size = pTrans->GetSize();
		angle += DEGTORAD(20) * deltaSecs;
		angle += m_angularVelocity *deltaSecs;

		IEventPtr pEvent(ALE_NEW Event_Move_Actor_2D(m_pOwner->GetId(), position, angle, size));
		IEventManager::Get()->VQueueEvent(pEvent);
	}
}

#pragma warning( default : 4244)

ActorComponent* CreateMoveComponent2D()
{
	return ALE_NEW MoveComponent2D();
}